<?php
// +----------------------------------------------------------------------
// | Bwsaas
// +----------------------------------------------------------------------
// | Copyright (c) 2015~2020 http://www.buwangyun.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Gitee ( https://gitee.com/buwangyun/bwsaas )
// +----------------------------------------------------------------------
// | Author: buwangyun <hnlg666@163.com>
// +----------------------------------------------------------------------
// | Date: 2020-9-28 10:55:00
// +----------------------------------------------------------------------

namespace buwang\base;

use think\facade\View;
use app\manage\model\Member;

class Manage extends BaseController
{
    protected $uid;
    protected $sub_id;
    protected $web_config;

    /**
     * 当前模型
     * @Model
     * @var object
     */
    protected $model;
    /**
     * 模板布局, false取消
     * @var string|bool
     */
    protected $layout = '../../../view/public/layout';
    /**
     * 字段排序
     * @var array
     */
    protected $sort = [
        'id' => 'desc',
    ];

    /**
     * 允许修改的字段
     * @var array
     */
    protected $allowModifyFileds = [
        'status',
        'sort',
        'remark',
        'is_delete',
        'is_auth',
        'title',
    ];

    /**
     * 不导出的字段信息
     * @var array
     */
    protected $noExportFileds = ['delete_time', 'update_time'];

    /**
     * 下拉选择条件
     * @var array
     */
    protected $selectWhere = [];

    /**
     * 是否关联查询
     * @var bool
     */
    protected $relationSearch = false;

    // 初始化
    protected function initialize()
    {
        parent::initialize();
        $this->uid = isset($this->user->id) ? $this->user->id : 0;
        $this->sub_id = isset($this->user->sub_member_id) ? $this->user->sub_member_id : 0;
        if($this->sub_id){
            $this->uid = $this->user->top_id;
            $this->user->id = $this->user->top_id;
        }
        $this->web_config = bw_config('web_config'); //当前站点配置
        // 模板全局变量赋值
        View::assign('web_config', $this->web_config);
        // 模板全局变量赋值用户信息
        View::assign('user', $this->user);
    }

    /**
     * 禁止用户登录
     */
    protected function isUserAuth($code = 401)
    {
        if (!$this->user) {
            $this->code($code)->error_jump('API验证获取用户信息失败');
        }
    }

    //得到需要保存到数据库的用户id
    protected function getSaveDataUid()
    {
        $uid = -1;
        $scopes = isset($this->request->scopes) ? $this->request->scopes : false;
        if ($scopes !== false) {
            switch ($scopes) {
                case "admin":
                    $uid = 0;
                    break;
                case "member":
                    //查询顶级租户
                    $uid = isset($this->request->top_user) ? $this->request->top_user['id'] : -1;
                    break;
            }
        }
        return $uid;
    }

    /**
     * 模板变量赋值
     * @param string|array $name 模板变量
     * @param mixed $value 变量值
     * @return mixed
     */
    protected function assign($name, $value = null)
    {
        return $this->app->view->assign($name, $value);
    }

    /**
     * 解析和获取模板内容 用于输出
     * @param string $template
     * @param array $vars
     * @return mixed
     */
    protected function fetch($template = '', $vars = [])
    {
        return $this->app->view->fetch($template, $vars);
    }

    /**
     * 重写验证规则
     * @param array $data
     * @param array|string $validate
     * @param array $message
     * @param bool $batch
     * @return array|bool|string|true
     */
    protected function validate(array $data, $validate, array $message = [], bool $batch = false)
    {
//        try {
        parent::validate($data, $validate, $message, $batch);
//        } catch (\Exception $e) {
//            return $this->error($e->getMessage());
//        }
        return true;
    }

    /**
     * 构建请求参数
     * @param array $excludeFields 忽略构建搜索的字段
     * @return array
     */
    protected function buildTableParames($excludeFields = [])
    {
        $get = $this->request->get('', null, null);
        $page = isset($get['page']) && !empty($get['page']) ? $get['page'] : 1;
        $limit = isset($get['limit']) && !empty($get['limit']) ? $get['limit'] : 15;
        $filters = isset($get['filter']) && !empty($get['filter']) ? $get['filter'] : '{}';
        $ops = isset($get['op']) && !empty($get['op']) ? $get['op'] : '{}';
        // json转数组
        $filters = json_decode($filters, true);
        $ops = json_decode($ops, true);
        $where = [];
        $excludes = [];

        // 判断是否关联查询
        $tableName = $this->getTableName();
        foreach ($filters as $key => $val) {
            if (in_array($key, $excludeFields)) {
                $excludes[$key] = $val;
                continue;
            }
            if (!preg_match('/^[a-zA-Z0-9_\-\.]+$/', $key)) {
                continue;
            }
            $op = strtoupper(isset($ops[$key]) && !empty($ops[$key]) ? $ops[$key] : '%*%');
            if (!empty($this->model) && $this->relationSearch && count(explode('.', $key)) == 2) {
                $key = "{$tableName}.{$key}";
            }
            switch ($op) {
                case '=':
                    $where[] = [$key, '=', $val];
                    break;
                case 'LIKE':
                case '%*%':
                    $where[] = [$key, 'LIKE', "%{$val}%"];
                    break;
                case '*%':
                    $where[] = [$key, 'LIKE', "{$val}%"];
                    break;
                case '%*':
                    $where[] = [$key, 'LIKE', "%{$val}"];
                    break;
                case 'RANGE':
                    if(!is_string($val)){
                        continue 2;
                    }
                    [$beginTime, $endTime] = explode(' - ', $val);
                    $where[] = [$key, '>=', strtotime($beginTime)];
                    $where[] = [$key, '<=', strtotime($endTime)];
                    break;
                case 'BETWEEN':
                case 'NOT BETWEEN'://TODO 修复完善范围查询条件
                    $arr = array_slice(explode(',', $val), 0, 2);
                    if (stripos($val, ',') === false || !array_filter($arr, function ($v) {
                            return $v != '' && $v !== false && $v !== null;
                        })) {
                        continue 2;
                    }
                    //当出现一边为空时改变操作符
                    if ($arr[0] === '') {
                        $op = $op == 'BETWEEN' ? '<=' : '>';
                        $arr = $arr[1];
                    } elseif ($arr[1] === '') {
                        $op = $op == 'BETWEEN' ? '>=' : '<';
                        $arr = $arr[0];
                    }
                    $where[] = [$key, $op, $arr];
                    break;
                case 'IN': //增加in类型查询
                case 'NOT IN':
                    $where[] = [$key, $op, is_array($val) ? $val : explode(',', $val)];
                    break;
                default:
                    $where[] = [$key, $op, "%{$val}"];
            }
        }
        return [$page, $limit, $where, $excludes];
    }

    /**
     * 下拉选择列表
     * @return \think\Response
     */
    public function selectList()
    {
        $fields = input('selectFieds');
        $data = $this->model
            ->where($this->selectWhere)
            ->field($fields)
            ->select();
        return $this->success("获取成功", $data);
    }

    /**
     * 获取当前model的表别名
     * @return string
     */
    protected function getTableName()
    {
        //return \think\helper\Str::snake(class_basename($this->model));
        if (!$this->model) {
            return ''; // 或抛出异常
        }

        // 优先级1：直接获取表名属性
        if (property_exists($this->model, 'table') && $this->model->table) {
            return $this->model->table;
        }

        // 优先级2：调用 getName() 方法
        if (method_exists($this->model, 'getName')) {
            return \buwang\util\CommonTool::humpToLine(lcfirst($this->model->getName()));
        }

        // 优先级3：通过类名推断
        return \think\helper\Str::snake(class_basename($this->model));
    }
}